<template>
    <div class="app-upload" :class="{'no-upload': noUpload}">
        <el-upload 
            :action="action" 
            :list-type="listType" 
            :on-preview="onPreview" 
            :on-success="onSuccess" 
            :on-error="onError" 
            :on-change="onChange" 
            :on-remove="onRemove" 
            :file-list="fileLists">
            <i class="el-icon-plus"></i>
            <slot name="tip"></slot>
        </el-upload>
    </div>
</template>
<script>
export default {
    props: {
        action: {
            type: String,
            required: true
        },
        listType: String,

        formData: Object, //表单对象
        formKey: String, //要赋值的表单key
        maxNum: Number, //最多上传文件数

        multiple: Boolean,
        accept: String,
    },
    data() {
        return {
            noUpload: false,
            fileListDemo:  [{name: '', url: ''}]
        }
    },
    computed:{
        fileLists(){
            let arr = []
            let formData = this.formData[this.formKey]
            if(this.maxNum === 1){
                arr = !!formData ? [{url: formData}] : []
            }else{
                if(!!formData){
                    try{
                        formData.split(',').forEach(img => {
                            arr.push({url: img})
                        })
                    }catch(err){
                        console.log(err)
                    }
                }
            }
            return arr
        }
    },
    watch: {
        fileLists: {
            handler: function(val){
                this.noUpload = (val.length === this.maxNum)
            },
            deep: true
        }
    },
    methods: {
        onSuccess(response, file, fileList) {
            if(response.code === 500){
                this.$message.error('图片格式不正确')
            }else{
                if(this.formData[this.formKey]){
                    if(this.maxNum === 1){
                        this.formData[this.formKey] = response.imgName[0]
                    }else{
                        this.formData[this.formKey] += ',' + response.imgName[0]
                    }
                }else{
                    this.formData[this.formKey] = response.imgName[0]
                }
                this.noUpload = fileList.length === this.maxNum
            }
        },
        onError(err, file, fileList){
            this.$message.error('上传失败')
            fileList = []
            this.noUpload = fileList.length === this.maxNum
        },
        beforeUpload(file) {
            if(file) this.noUpload = true
            let size = Math.ceil(file.size / 1024)
            let maxsize = 500
            let ok = true
            if (size > maxsize) {
                this.$message.warning('您上传的图片大小为' + file.size + 'kb，超过了' + maxsize + 'kb的限制');
                ok = false
                this.noUpload = false
            }
            return ok
        },
        onPreview(file) {
            console.log('on preview')
            console.log(file.url)
            let div = document.createElement('div')
            let img = document.createElement('img')
            div.setAttribute('class', 'app-img-previewer')
            div.setAttribute('id', 'app-img-previewer')
            img.src = file.url
            div.appendChild(img)
            div.addEventListener('click', function(){
                document.body.removeChild(document.getElementById('app-img-previewer'))
            }, false)
            document.body.appendChild(div)
        },
        onRemove(file, fileList){
            console.log('file: ', file)
            console.log('fileList: ', fileList)
            this.noUpload = fileList.length === this.maxNum
            this.formData[this.formKey] = fileList.map(v => v.url).join(',')
        },
        onChange(file, fileList){
            this.noUpload = fileList.length === this.maxNum
        }
    },
    created(){
        this.noUpload = (this.fileLists.length === this.maxNum)
    }
}
</script>

<style lang="less">
.app-upload{
    .el-upload--picture-card{
        width: 120px;
        height: 120px;
        line-height: 118px;
    }
    .el-upload-list--picture-card{
        .el-upload-list__item{
            width: 122px;
            height: 122px;
        }
    }

    &.no-upload{
        .el-upload{
            display: none;
        }
    }
}
.app-img-previewer{
    position: fixed;
    z-index: 9999;
    width: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-x: hidden;
    overflow: auto;
    padding: 0;
    background-color: rgba(255,255,255,.8);
    img{
        position: absolute;
        top:50%;
        left: 50%;
        transform: translate(-50%,-50%);
        display: block;
        // margin: 40px auto;
        cursor: zoom-out;
    }
}
</style>